#pragma once
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "../comm/logger.hpp"
#include "../comm/util.hpp"
namespace ns_runner
{
    using namespace ns_util;
    class Runner
    {
    private:
        static void SetProcLimit(int cpu_limit, int mem_limit) // 前者设置程序运行时间,后者限制程序内存大小
        {
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_cur = cpu_limit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);
            struct rlimit mem_rlimit;
            mem_rlimit.rlim_cur = mem_limit * 1024; // 设置为kb单位
            mem_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }

    public:
        Runner()
        {
        }
        ~Runner()
        {
        }
        // 返回值<0,内部错误,>0,不同的退出码,==0,成功执行
        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {
            // 重定向出运行所需要的文件
            std::string _exec = Path_Util::Exe(file_name);
            std::string _stdin = Path_Util::Stdin(file_name);
            std::string _stdout = Path_Util::Stdout(file_name);
            std::string _stderr = Path_Util::Stderr(file_name);
            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                ELOG("打开标准文件失败");
                return -1; //-1说明打开文件失败
            }
            pid_t pid = fork();
            if (pid < 0)
            {
                ELOG("内部错误,创建子进程失败");
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                return -2; //-2说明创建子进程失败
            }
            else if (pid == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);
                SetProcLimit(cpu_limit, mem_limit);
                execl(_exec.c_str(), _exec.c_str(), nullptr);
                exit(1);
            }
            else
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                int status = 0;
                waitpid(pid, &status, 0); // 程序运行异常,一定是收到了信号,这里可以捕获到信号判断出错类型
                //(status & 0x7F)  提取导致子进程终止的信号编号(低位7个)
                ILOG("程序正常退出,退出码为%d",(status & 0x7F));
                return (status & 0x7F);
            }
        }
    };
}